// pages/myself/store/StoreInfo.js
var Zan = require('../../../dist/index');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
let WxNotificationCenter = require('../../../utils/WxNotificationCenter.js');
var network = null;
var utils = null;
var api = null;
const app = getApp();
var start = 0;

Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    region: [],
    store:null,
    shopInfo: null,
    // address: '点击获取当前位置',
    lng: 0,
    lat: 0,
    backTag: 0, // 0进入详情页，1返回上一页（点击列的时候使用）
    nodata: {
      msg: '该区暂无门店',
      notype: 2,
      imgurl: '/images/nodatas.png',
      nourl: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    this.setData({
      lng: options.lng,
      lat: options.lat,
      backTag: options.backTag,
      region: [app.globalData.store.province, app.globalData.store.city, app.globalData.store.district]
    })
    this.onPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      store: app.globalData.store
    })
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    start = 0;
    wx.stopPullDownRefresh();
    this.setData({
      shopInfo: [],
    });
    network._post_page_json(this, api.searchStore, start, { searchArea: [this.data.region[0], this.data.region[1], this.data.region[2]], lat: this.data.lat, lng: this.data.lng }, success);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.shopInfo.length < this.data.recordsTotal) {
      start = start + 20;
      network._post_page_json(this, api.searchStore, start, { searchArea: [this.data.region[0], this.data.region[1], this.data.region[2]], lat: this.data.lat, lng: this.data.lng }, success);
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  handler:function(e){
    let that = this;
    console.log(e.detail.authSetting['scope.userLocation']);
    if (e.detail.authSetting['scope.userLocation']) {
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          console.log("允许获取地理位置++++++++++++++++++");
          let latitude = res.latitude;
          let longitude = res.longitude;
          that.setData({
            lng: longitude,
            lat: latitude
          })
          network._post_json(that, api.nearbyStore, { lng: longitude, lat: latitude }, successStore);
        }
      })
    }
    
  },

  toDetails: function (e) {
    let item = e.currentTarget.dataset.item;
    if (this.data.backTag == 1) {
      WxNotificationCenter.postNotificationName("GetStoreInfo", item);
      wx.navigateBack();
    } else {
      wx.navigateTo({
        url: '/pages/myself/store/StoreDetails?store=' + encodeURIComponent(JSON.stringify(item))
      })
    }
  },
  search: function (e) {
    start = 0;
    wx.stopPullDownRefresh();
    this.setData({
      shopInfo: [],
      value: e.detail.value
    });
    if (this.data.value) {
      network._post_page_json(this, api.searchStore, start, { searchArea: [this.data.region[0], this.data.region[1], this.data.region[2]],lat: this.data.lat, lng: this.data.lng, searchWord: e.detail.value }, success);
    } else {
      network._post_page_json(this, api.searchStore, start, { searchArea: [this.data.region[0], this.data.region[1], this.data.region[2]], lat: this.data.lat, lng: this.data.lng }, success);
    }
  },
  bindRegionChange:function(e){
    console.log("选择的城市:", e.detail.value)
    this.setData({
      shopInfo:[],
      region: e.detail.value
    })
    network._post_page_json(this, api.searchStore, start, { searchArea: [this.data.region[0], this.data.region[1], this.data.region[2]],lat: this.data.lat, lng: this.data.lng}, success);

  }

}))

// 获取门店列表结果
var success = function (that, res) {
  var date = new Date();
  var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  var currentdate = h + ":" + m + ":" + s;
  if (res.data.data) {
    for (let i = 0; i < res.data.data.length; i++) {
      res.data.data[i].distance = parseInt(res.data.data[i].distance);
      res.data.data[i].km = parseInt(res.data.data[i].distance / 10) / 100;
      res.data.data[i].batting = false;
      if (res.data.data[i].openTime > currentdate || res.data.data[i].closeTime < currentdate){
        res.data.data[i].batting = true;
      }
    }
    that.setData({
      shopInfo: that.data.shopInfo.concat(res.data.data),
      recordsTotal: res.data.data.length
    })
  } else {
    that.showZanToast('该区暂时没有开放门店！');
  }
}

var successStore = function (that, res) {
  if (res.data.data) {
    app.globalData.store = res.data.data;
    app.globalData.isFacePayment = res.data.data.isFacePayment;


    start = 0;
    that.setData({
      shopInfo: [],
      region: [res.data.data.province, res.data.data.city, res.data.data.district]
    });
    network._post_page_json(that, api.searchStore, start, { searchArea: [that.data.region[0], that.data.region[1], that.data.region[2]], lat: that.data.lat, lng: that.data.lng }, success);
  }
}
